package ui.swing.common;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import ui.swing.Console;


public class ShowSuppoertedListener extends JApplet {

	private static Pattern p = Pattern.compile(".*\\.(add\\w+Listener\\().*\\.(\\w+\\))");

	JPanel pnlNorth;

	JPanel pnlResult;

	JTextField txtClassName;

	JButton btnOK;
	
	JScrollPane spResult;

	JTextArea taResult;

	@Override
	public void init() {
		getContentPane().add(getPnlNorth(), BorderLayout.NORTH);
		getContentPane().add(getPnlResult(), BorderLayout.CENTER);
		registerListener();
	}

	private JPanel getPnlNorth() {
		if (pnlNorth == null) {
			pnlNorth = new JPanel();
			Box hBox = Box.createHorizontalBox();
			hBox.add(new JLabel("类名: "));
			hBox.add(getTxtClassName());
			hBox.add(getBtnOK());
			pnlNorth.add(hBox);
		}
		return pnlNorth;
	}

	private JPanel getPnlResult() {
		if (pnlResult == null) {
			pnlResult = new JPanel(new BorderLayout());
			pnlResult.add(getSpResult());
		}
		return pnlResult;
	}

	private JButton getBtnOK() {
		if (btnOK == null) {
			btnOK = new JButton("OK");
		}
		return btnOK;
	}

	private JTextArea getTaResult() {
		if (taResult == null) {
			taResult = new JTextArea();
		}
		return taResult;
	}

	private JTextField getTxtClassName() {
		if (txtClassName == null) {
			txtClassName = new JTextField();
			txtClassName.setPreferredSize(new Dimension(150, 20));
		}
		return txtClassName;
	}

	private void registerListener() {
		getBtnOK().addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				findAndShow();
			}
		});
	}

	private void findAndShow() {
		String clsName = getTxtClassName().getText();
		try {
			Class clz = Class.forName("javax.swing." + clsName);
			Method[] methods = clz.getMethods();
			getTaResult().setText("");
			for (int i = 0; i < methods.length; i++) {
				String methodString = methods[i].toString();
				Matcher m = p.matcher(methodString);
				if(m.matches()) {
					getTaResult().append(m.group(1));
					getTaResult().append(m.group(2));
					getTaResult().append("\n");
				}
			}
		} catch (ClassNotFoundException e) {
			getTaResult().setText("<html><font color=red>类名无效</font></html>");
		}
	}

	public static void main(String[] args) {
		Console.run(new ShowSuppoertedListener(), 300, 300);
	}

	private JScrollPane getSpResult() {
		if(spResult == null) {
			spResult = new JScrollPane(getTaResult());
		}
		return spResult;
	}
}
